﻿namespace ConfigDatabase.Class
{
    using Npgsql;
    using System;
    using System.Data;
    using System.IO;
    using System.Security.AccessControl;

    public class SetupDatabase
    {
        private ConnectDatabase _condata;

        public SetupDatabase()
        {
            this._condata = new ConnectDatabase();
        }

        public SetupDatabase(ConnectDatabase condata)
        {
            this._condata = condata;
        }

        public void CapNhatFileConnect()
        {
            this._condata.Database = "camdo";
            this._condata.IpAdress = "localhost";
            this._condata.PassWord = "trancaovu1988";
            this._condata.Port = 0x1538;
            this._condata.Schema = "cvsoft";
            this._condata.User = "cvsoft";
            this._condata.SaveFileConnect();
        }

        public bool CreatTablespace(ConnectDatabase condata, string path, string owner, string tablespaceName, string role)
        {
            bool flag;
            NpgsqlConnection connect = new NpgsqlConnection(condata.StringConnect);
            try
            {
                connect.Open();
                flag = this.CreatTablespace(connect, path, owner, tablespaceName, role);
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.ToString(), "CreateTableSpace", "configdatabase.cs");
                flag = false;
            }
            finally
            {
                connect.Close();
                connect.Dispose();
            }
            return flag;
        }

        public bool CreatTablespace(NpgsqlConnection connect, string path, string owner, string tablespaceName, string role)
        {
            bool flag;
            try
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }
                Directory.CreateDirectory(path);
                DirectoryInfo info = new DirectoryInfo(path);
                DirectorySecurity accessControl = Directory.GetAccessControl(path);
                DirectorySecurity directorySecurity = info.GetAccessControl();
                string identity = Environment.UserDomainName + @"\" + owner;
                directorySecurity.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                info.SetAccessControl(directorySecurity);
                NpgsqlCommand command = new NpgsqlCommand("drop TABLESPACE " + tablespaceName, connect) {
                    CommandType = CommandType.Text
                };
                try
                {
                    command.ExecuteNonQuery();
                }
                catch
                {
                }
                string str2 = "CREATE TABLESPACE " + tablespaceName + "  OWNER " + role + "  LOCATION '" + path.Replace(@"\", "//") + "';";
                command.CommandText = str2;
                try
                {
                    flag = command.ExecuteNonQuery() != 0;
                }
                catch (NpgsqlException exception)
                {
                    ConnectDatabase.TrackingError(exception.ToString(), "createtablespace", "configdatabase.cs");
                    flag = false;
                }
            }
            catch (Exception exception2)
            {
                ConnectDatabase.TrackingError(exception2.ToString(), "CreateTableSpace", "configdatabase.cs");
                flag = false;
            }
            return flag;
        }

        public bool KiemTraDaTaoUser(string username)
        {
            bool flag;
            string selectCommandText = "select * from pg_catalog.pg_user where usename='" + username + "'";
            NpgsqlConnection selectConnection = new NpgsqlConnection(this._condata.StringConnect);
            try
            {
                selectConnection.Open();
                NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(selectCommandText, selectConnection);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                flag = dataTable.Rows.Count == 1;
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.Message, "KiemTraDaTaoUser", "Database.cs");
                flag = false;
            }
            finally
            {
                selectConnection.Close();
                selectConnection.Dispose();
            }
            return flag;
        }

        public bool KiemTraKetNoi()
        {
            return this.KiemTraKetNoi("");
        }

        public bool KiemTraKetNoi(string databaseName)
        {
            bool flag;
            string selectCommandText = "select * from pg_catalog.pg_database where 1=1";
            selectCommandText = selectCommandText + ((databaseName == "") ? "" : (" and datname='" + databaseName + "'"));
            NpgsqlConnection selectConnection = new NpgsqlConnection(this._condata.StringConnect);
            try
            {
                selectConnection.Open();
                NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(selectCommandText, selectConnection);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                flag = dataTable.Rows.Count > 0;
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.ToString(), "KiemTraKetNoi", "Database.cs");
                flag = false;
            }
            finally
            {
                selectConnection.Close();
                selectConnection.Dispose();
            }
            return flag;
        }

        public bool ResetPasswordDefault()
        {
            this._condata.PassWord = "enterprisedb123456";
            this._condata.SaveFileConnect();
            return this.TaoLaiMatKhau("enterprisedb", "enterprisedb");
        }

        private bool TaoLaiMatKhau(string user, string matkhau)
        {
            bool flag;
            string cmdText = "alter role " + user + " with password '" + matkhau + "'";
            NpgsqlConnection connection = new NpgsqlConnection(this._condata.StringConnect);
            try
            {
                connection.Open();
                new NpgsqlCommand(cmdText, connection) { CommandType = CommandType.Text }.ExecuteNonQuery();
                flag = true;
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.Message, "TaoLaiMatKhau", "Database.cs");
                flag = false;
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }
            return flag;
        }

        private bool TaoLaiMatKhau(NpgsqlConnection connect, string user, string matkhau)
        {
            string cmdText = "alter role " + user + " with password '" + matkhau + "'";
            try
            {
                new NpgsqlCommand(cmdText, connect) { CommandType = CommandType.Text }.ExecuteNonQuery();
                return true;
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.Message, "TaoLaiMatKhau", "Database.cs");
                return false;
            }
        }

        public bool ThietLapDatabase(string role, string password, string databasename, string schema)
        {
            bool flag;
            this._condata = new ConnectDatabase();
            string cmdText = ("CREATE ROLE " + role + " LOGIN password '" + password + "' superuser ") + " inherit createdb createrole;";
            NpgsqlConnection connection = new NpgsqlConnection(this._condata.StringConnect);
            try
            {
                connection.Open();
                NpgsqlCommand command = new NpgsqlCommand(cmdText, connection) {
                    CommandType = CommandType.Text
                };
                int num = -1;
                if (!this.KiemTraDaTaoUser(role))
                {
                    num = command.ExecuteNonQuery();
                }
                if (num != 0)
                {
                    if (this.CreatTablespace(connection, @"C:\TableSpace\tb_" + databasename, "enterprisedb", "tb_" + databasename, role))
                    {
                        command = new NpgsqlCommand("create database " + databasename + " owner " + role + " tablespace tb_" + databasename + " template template0 encoding='utf8';", connection) {
                            CommandType = CommandType.Text
                        };
                        num = -1;
                        if (!this.KiemTraKetNoi(databasename))
                        {
                            num = command.ExecuteNonQuery();
                        }
                        if (num != 0)
                        {
                            if (!this.TaoLaiMatKhau("enterprisedb", "enterprisedb123456"))
                            {
                                command.CommandText = "drop database " + databasename + ";drop tablespace tb_" + databasename + ";drop role " + role;
                                command.ExecuteNonQuery();
                            }
                            this._condata.Database = databasename;
                            this._condata.PassWord = password;
                            this._condata.Schema = schema;
                            this._condata.User = role;
                            this._condata.SaveFileConnect();
                        }
                    }
                    else
                    {
                        command.CommandText = "drop role " + role;
                        command.ExecuteNonQuery();
                    }
                }
                flag = num != 0;
            }
            catch (NpgsqlException exception)
            {
                ConnectDatabase.TrackingError(exception.Message, "ThietLapDatabase", "Database.cs");
                flag = false;
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }
            return flag;
        }
    }
}

